<template>
  <s-layout title="订单支付" :bg-style="{ backgroundColor: '#f5f5f5' }">
    <view class="pay-container">
      <!-- 倒计时 -->
      <view class="countdown-section">
        <text class="countdown-label">支付时间剩余</text>
        <text class="countdown-time">{{ countdownText }}</text>
      </view>

      <!-- 门店信息 -->
      <view class="store-section">
        <view class="store-logo">
          <image :src="storeLogo" mode="aspectFill"></image>
        </view>
        <view class="store-info">
          <view class="store-name">{{ storeName }}</view>
          <view class="store-tag">{{ eatTypeText }}</view>
        </view>
        <view class="store-price">
          <text class="price-symbol">¥</text>
          <text class="price-value">{{ formatPrice(localOrder.payAmount) }}</text>
          <text class="price-count">x{{ totalCount }}</text>
        </view>
      </view>

      <!-- 商品备注 -->
      <!-- <view class="note-section" v-if="orderDetail.note">
        <text class="note-label">商品备注</text>
      </view> -->

      <!-- 金额明细 -->
      <view class="amount-section">
        <view class="amount-title">金额明细</view>
        <view class="amount-item">
          <text class="amount-label">订单金额</text>
          <text class="amount-value">¥{{ formatPrice(localOrder.totalAmount) }}</text>
        </view>
        <view class="amount-item">
          <text class="amount-label">待支付</text>
          <text class="amount-value highlight">¥{{ formatPrice(localOrder.payAmount) }}</text>
        </view>
      </view>

      <!-- 福利卡 -->
      <!-- <view class="welfare-section" @click="selectCard">
        <text class="welfare-label">福利卡</text>
        <view class="welfare-select">
          <text class="select-text">{{ selectedCard || '选择福利卡' }}</text>
          <uni-icons type="right" size="16" color="#999"></uni-icons>
        </view>
      </view> -->

      <!-- 积分 -->
      <!-- <view class="points-section">
        <text class="points-label">积分</text>
        <view class="points-value">
          <text class="points-num">-¥0</text>
          <uni-icons 
            :type="usePoints ? 'checkbox-filled' : 'circle'" 
            :color="usePoints ? '#e4393c' : '#ccc'" 
            size="20"
            @click="togglePoints"
          ></uni-icons>
        </view>
      </view> -->

      <!-- 订单信息 -->
      <view class="order-info-section">
        <view class="info-item">
          <text class="info-label">订单编号：</text>
          <text class="info-value">{{ localOrder.orderSn }}</text>
          <text class="copy-btn" @click="copyOrderSn">复制</text>
        </view>
        <view class="info-item">
          <text class="info-label">创建时间：</text>
          <text class="info-value">{{ formatTime(localOrder.createTime) }}</text>
        </view>
      </view>

      <!-- 联系客服 -->
      <view class="contact-section" @click="contactService">
        <uni-icons type="phone" size="18" color="#e4393c"></uni-icons>
        <text class="contact-text">联系客服</text>
      </view>

      <!-- 底部支付栏 -->
      <view class="bottom-bar">
        <view class="pay-info">
          <text class="pay-label">待支付</text>
          <text class="pay-amount">¥{{ formatPrice(localOrder.payAmount) }}</text>
        </view>
        <view class="pay-btn" @click="goPay">继续付款</view>
      </view>
    </view>
  </s-layout>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import sheep from '@/sheep';

// 数据
const orderId = ref('');
const localOrder = ref({});
const cateringOrder = ref({});
const thirdOrderDetail = ref({});
const selectedCard = ref('');
const usePoints = ref(false);
const countdownSeconds = ref(0);
const timer = ref(null);

// KFC默认logo
const defaultLogo = 'https://kfccatering-static.oss-cn-beijing.aliyuncs.com/logo/kfc-logo.png';

// 倒计时文本
const countdownText = computed(() => {
  const seconds = countdownSeconds.value;
  if (seconds <= 0) return '00:00:00';
  
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const secs = seconds % 60;
  
  return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
});

// 商品总数
const totalCount = computed(() => {
  // 优先从 thirdOrderDetail.productsInfo 解析
  if (thirdOrderDetail.value.productsInfo) {
    try {
      const productList = JSON.parse(thirdOrderDetail.value.productsInfo);
      return productList.reduce((total, item) => total + (item.quantity || 1), 0);
    } catch (e) {
      console.error('【订单支付】解析商品信息失败:', e);
    }
  }
  
  // 备用：从 thirdOrderDetail.count
  if (thirdOrderDetail.value.count) {
    return thirdOrderDetail.value.count;
  }
  
  // 兜底：从 localOrder.productInfo
  if (localOrder.value.productInfo) {
    return localOrder.value.productInfo.reduce((total, item) => total + (item.buyNum || 0), 0);
  }
  
  return 1;
});

// 门店Logo
const storeLogo = computed(() => {
  const cateringStore = sheep.$store('catering');
  return cateringStore.storeInfo?.logo || defaultLogo;
});

// 门店名称
const storeName = computed(() => {
  // 优先从 thirdOrderDetail 获取
  if (thirdOrderDetail.value.shopName) {
    return thirdOrderDetail.value.shopName;
  }
  
  // 备用：从 cateringOrder
  if (cateringOrder.value.shopName) {
    return cateringOrder.value.shopName;
  }
  
  // 兜底：从 store
  const cateringStore = sheep.$store('catering');
  return cateringStore.storeInfo?.name || '门店';
});

// 用餐方式文本
const eatTypeText = computed(() => {
  // 优先从 thirdOrderDetail 获取（已经是文本）
  if (thirdOrderDetail.value.eatTypeName) {
    return thirdOrderDetail.value.eatTypeName;
  }
  
  // 备用：从 cateringOrder 数字转文本
  const eatType = cateringOrder.value.eatType;
  if (eatType === 0) return '堂食';
  if (eatType === 1) return '打包';
  if (eatType === 2) return '外卖';
  
  return '堂食';
});

// 页面加载
onLoad(async (options) => {
  if (options.orderId) {
    orderId.value = options.orderId;
    await loadOrderDetail();
  } else {
    uni.showToast({
      title: '订单ID不存在',
      icon: 'none'
    });
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  }
});

// 加载订单详情
async function loadOrderDetail() {
  try {
    uni.showLoading({ title: '加载中...' });
    
    const res = await sheep.$api.catering.getOrderDetail(orderId.value);
    
    uni.hideLoading();
    
    if (res.code === 200 && res.data) {
      localOrder.value = res.data.localOrder || {};
      cateringOrder.value = res.data.cateringOrder || {};
      thirdOrderDetail.value = res.data.thirdOrderDetail || {};
      
      console.log('【订单支付】订单详情:', {
        localOrder: localOrder.value,
        cateringOrder: cateringOrder.value,
        thirdOrderDetail: thirdOrderDetail.value
      });
      
      // ❌ 注释掉：不再从第三方价格覆盖系统价格，使用 localOrder 自己的价格
      // if (thirdOrderDetail.value.totalUserPrice) {
      //   localOrder.value.payAmount = thirdOrderDetail.value.totalUserPrice;
      //   localOrder.value.totalAmount = thirdOrderDetail.value.totalUserPrice;
      // }
      
      console.log('【订单支付】使用系统内部价格:', {
        payAmount: localOrder.value.payAmount,
        totalAmount: localOrder.value.totalAmount
      });
      
      // 计算倒计时（20分钟 = 1200秒）
      if (localOrder.value.createTime) {
        const createTime = new Date(localOrder.value.createTime).getTime();
        const expireTime = createTime + (20 * 60 * 1000); // 创建时间 + 20分钟
        const now = Date.now();
        countdownSeconds.value = Math.max(0, Math.floor((expireTime - now) / 1000));
        
        console.log('【订单支付】倒计时信息:', {
          createTime: new Date(createTime).toLocaleString(),
          expireTime: new Date(expireTime).toLocaleString(),
          remainSeconds: countdownSeconds.value
        });
        
        // 如果已超时
        if (countdownSeconds.value <= 0) {
          showTimeoutDialog();
        } else {
          startCountdown();
        }
      }
    } else {
      uni.showToast({
        title: res.msg || '加载失败',
        icon: 'none'
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error('【订单支付】加载订单详情失败:', error);
    uni.showToast({
      title: '加载失败，请重试',
      icon: 'none'
    });
  }
}

// 开始倒计时
function startCountdown() {
  if (timer.value) {
    clearInterval(timer.value);
  }
  
  timer.value = setInterval(() => {
    if (countdownSeconds.value > 0) {
      countdownSeconds.value--;
    } else {
      clearInterval(timer.value);
      showTimeoutDialog();
    }
  }, 1000);
}

// 显示超时对话框
function showTimeoutDialog() {
  uni.showModal({
    title: '订单已超时',
    content: '该订单已超过支付时间，已自动取消',
    showCancel: false,
    confirmText: '我知道了',
    success: (res) => {
      if (res.confirm) {
        uni.navigateBack();
      }
    }
  });
}

// 格式化价格
function formatPrice(price) {
  if (!price && price !== 0) return '0.00';
  return Number(price).toFixed(2);
}

// 格式化时间
function formatTime(timeStr) {
  if (!timeStr) return '';
  const date = new Date(timeStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 选择福利卡
function selectCard() {
  uni.showToast({
    title: '福利卡功能开发中',
    icon: 'none'
  });
}

// 切换积分使用
function togglePoints() {
  usePoints.value = !usePoints.value;
}

// 复制订单号
function copyOrderSn() {
  if (!localOrder.value.orderSn) {
    uni.showToast({
      title: '订单号不存在',
      icon: 'none'
    });
    return;
  }
  
  uni.setClipboardData({
    data: localOrder.value.orderSn,
    success: () => {
      uni.showToast({
        title: '复制成功',
        icon: 'success'
      });
    }
  });
}

// 联系客服
function contactService() {
  uni.showToast({
    title: '客服功能开发中',
    icon: 'none'
  });
}

// 去支付
function goPay() {
  if (countdownSeconds.value <= 0) {
    uni.showToast({
      title: '订单已超时',
      icon: 'none'
    });
    return;
  }
  
  // 显示加载提示，提升用户体验
  uni.showLoading({
    title: '跳转支付...',
    mask: true
  });
  
  // 延迟跳转，让加载提示更自然
  setTimeout(() => {
    uni.hideLoading();
    
    // 获取品牌信息
    const cateringStore = sheep.$store('catering');
    const brandOt = cateringStore.storeInfo?.ot || 1;
    const brandName = cateringStore.storeInfo?.name || '肯德基';
    
    // 跳转到统一支付页面，传递订单ID、金额及品牌信息
    sheep.$router.redirect('/pages/pay/index', {
      id: localOrder.value.payId,  // 订单ID（数字）
      orderSN: localOrder.value.payId,  // 兼容旧字段
      totalAmount: formatPrice(localOrder.value.payAmount),  // 支付金额
      type: 'goods',  // 订单类型
      brandOt: brandOt,  // 品牌类型
      brandName: brandName  // 品牌名称
    });
  }, 500);
}

// 页面卸载
onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value);
  }
});
</script>

<style lang="scss" scoped>
.pay-container {
  background-color: #f5f5f5;
  padding-bottom: 180rpx;
}

// 倒计时
.countdown-section {
  background: linear-gradient(135deg, #ff6b6b 0%, #e74c3c 100%);
  padding: 40rpx 30rpx;
  text-align: center;
  margin-bottom: 20rpx;
  
  .countdown-label {
    display: block;
    color: #fff;
    font-size: 28rpx;
    margin-bottom: 10rpx;
  }
  
  .countdown-time {
    display: block;
    color: #fff;
    font-size: 48rpx;
    font-weight: bold;
    letter-spacing: 4rpx;
  }
}

// 门店信息
.store-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
  
  .store-logo {
    width: 100rpx;
    height: 100rpx;
    border-radius: 10rpx;
    overflow: hidden;
    margin-right: 20rpx;
    
    image {
      width: 100%;
      height: 100%;
    }
  }
  
  .store-info {
    flex: 1;
    
    .store-name {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 10rpx;
    }
    
    .store-tag {
      display: inline-block;
      padding: 4rpx 12rpx;
      background-color: #f0f0f0;
      color: #666;
      font-size: 24rpx;
      border-radius: 4rpx;
    }
  }
  
  .store-price {
    text-align: right;
    
    .price-symbol {
      font-size: 28rpx;
      color: #e4393c;
    }
    
    .price-value {
      font-size: 40rpx;
      font-weight: bold;
      color: #e4393c;
    }
    
    .price-count {
      display: block;
      font-size: 24rpx;
      color: #999;
      margin-top: 5rpx;
    }
  }
}

// 商品备注
.note-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  
  .note-label {
    font-size: 28rpx;
    color: #333;
  }
}

// 金额明细
.amount-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  
  .amount-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }
  
  .amount-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15rpx 0;
    
    .amount-label {
      font-size: 28rpx;
      color: #666;
    }
    
    .amount-value {
      font-size: 28rpx;
      color: #333;
      
      &.highlight {
        font-size: 32rpx;
        font-weight: bold;
        color: #e4393c;
      }
    }
  }
}

// 福利卡
.welfare-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 1rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .welfare-label {
    font-size: 28rpx;
    color: #333;
  }
  
  .welfare-select {
    display: flex;
    align-items: center;
    
    .select-text {
      font-size: 28rpx;
      color: #999;
      margin-right: 10rpx;
    }
  }
}

// 积分
.points-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .points-label {
    font-size: 28rpx;
    color: #333;
  }
  
  .points-value {
    display: flex;
    align-items: center;
    
    .points-num {
      font-size: 28rpx;
      color: #666;
      margin-right: 20rpx;
    }
  }
}

// 订单信息
.order-info-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  
  .info-item {
    display: flex;
    align-items: center;
    padding: 10rpx 0;
    
    .info-label {
      font-size: 28rpx;
      color: #999;
    }
    
    .info-value {
      flex: 1;
      font-size: 28rpx;
      color: #333;
    }
    
    .copy-btn {
      padding: 4rpx 16rpx;
      background-color: #f0f0f0;
      color: #666;
      font-size: 24rpx;
      border-radius: 4rpx;
    }
  }
}

// 联系客服
.contact-section {
  background-color: #fff;
  padding: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .contact-text {
    font-size: 28rpx;
    color: #e4393c;
    margin-left: 10rpx;
  }
}

// 底部支付栏
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: space-between;
  align-items: center;
  z-index: 100;
  
  .pay-info {
    .pay-label {
      display: block;
      font-size: 24rpx;
      color: #999;
      margin-bottom: 5rpx;
    }
    
    .pay-amount {
      font-size: 36rpx;
      font-weight: bold;
      color: #e4393c;
    }
  }
  
  .pay-btn {
    background: linear-gradient(135deg, #ff6b6b 0%, #e74c3c 100%);
    color: #fff;
    font-size: 32rpx;
    font-weight: bold;
    border-radius: 50rpx;
    border: none;
    padding: 20rpx 60rpx;
    line-height: 1;
    
    // 清除uni-app button默认样式
    &::after {
      border: none;
    }
    
    // 重置所有button默认样式
    margin: 0;
    box-sizing: border-box;
  }
}
</style>

